from django.contrib.auth.models import Permission, Group
from django.contrib.contenttypes.models import ContentType
from rest_framework import serializers, status
from rest_framework.response import Response

from apps.contents.models import GoodsCategory, GoodsChannel
from apps.goods.models import SKU, SKUImage, SPU, SPUSpecification, SpecificationOption, SKUSpecification
from apps.users.models import User


def jwt_response_payload_handler(token, user=None, request=None):
  """
  自定义jwt认证成功返回数据
  """
  return {
    'token': token,
    'id': user.id,
    'username': user.username
  }



# ---------------自定义分页器----------------------

from rest_framework.pagination import PageNumberPagination
class PagNun(PageNumberPagination):
  page_size = 5
  page_size_query_param = 'pagesize'
  max_page_size = 5

  def get_paginated_response(self, data):
    return Response({
      'count': self.page.paginator.count,  # 总数量
      'lists': data,  # 用户数据
      'page': self.page.number,  # 当前页数
      'pages': self.page.paginator.num_pages,  # 总页数
      'pagesize': self.page_size  # 后端指定的页容量
    })


# ------------------------用户查询序列化器------------------------------------
class UserSearchSerializer(serializers.ModelSerializer):
    class Meta:
        model=User
        fields=('id','username','mobile','email')

    #自定义创建方法
    def create(self, validated_data):
        user=User.objects.create_user(**validated_data)
        return user

class GoodSkuSerializer(serializers.ModelSerializer):
    class Meta:
        model=SKUImage
        fields=('sku','image','id',)

#------------------spec规格选项序列化器-------------------------
class SpecSerializer(serializers.ModelSerializer):

    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()
    class Meta:
      model = SKUSpecification

      fields = ('spec_id','option_id')


class SkuInfoSerializer(serializers.ModelSerializer):

    specs = SpecSerializer(many=True)
    spu=serializers.StringRelatedField()
    category=serializers.StringRelatedField()

    spu_id = serializers.IntegerField()
    category_id = serializers.IntegerField()
    class Meta:
        model=SKU
        fields='__all__'

    def create(self, validated_data):

        spec=validated_data.pop('specs')

        from django.db import transaction

        while transaction.atomic():
          # 创建保存点
          save_id = transaction.savepoint()

          try:
            sku=SKU.objects.create(**validated_data)
          except Exception:
            # 回滚到保存点
            transaction.savepoint_rollback(save_id)
          for spec_data in spec:
              SKUSpecification.objects.create(sku=sku,**spec_data)

          # 提交从保存点到当前状态的所有数据库事务操作
          transaction.savepoint_commit(save_id)
          return sku

    def update(self, instance, validated_data):
        sku_id = self.instance.id
        spec_data = validated_data.pop('specs')

        SKU.objects.filter(id=sku_id).update(**validated_data)

        for spec in spec_data:
            spc_id=spec.get('spec_id')
            op_id=spec.get('option_id')
            SKUSpecification.objects.filter(sku_id=sku_id).update(spec_id=spc_id,option_id=op_id)

        return instance






#商品三级分类序列化器
class SkuCategoriesSerializer(serializers.ModelSerializer):
    class Meta:
        model=GoodsCategory
        fields =('id','name')

class SpuSimpleSerializer(serializers.ModelSerializer):
    class Meta:
      model = SPU
      fields = ('id', 'name')

class GoodsOptineSerializer(serializers.ModelSerializer):
    class Meta:
        model=SpecificationOption
        fields = '__all__'



class SpuSpecsSerializer(serializers.ModelSerializer):

    # spu = serializers.StringRelatedField()
    # spu_id = serializers.IntegerField()

    options=GoodsOptineSerializer(many=True)
    class Meta:
      model = SPUSpecification
      fields = '__all__'


#-------------------权限管理-----------------------

class PermissionSerializer(serializers.ModelSerializer):

    class Meta:
        model = Permission
        fields = '__all__'

class PermissionTypeSerializer(serializers.ModelSerializer):
    class Meta:
      model = ContentType
      fields = ('id','name')


#----------------------组管理--------------------------
class PermissionGroupSerializer(serializers.ModelSerializer):


    class Meta:
        model = Group
        fields='__all__'



class PermissionAdminSerializer(serializers.ModelSerializer):

    class Meta:
        model=User
        fields = '__all__'
        extra_kwargs= {
          'password':{
            'write_only':True
            }
        }

    def create(self, validated_data):

        admin = super().create(validated_data)
        admin.set_password(validated_data['password'])
        admin.is_staff=True
        admin.save()

        return admin




